package com.bawei.mvvm.http;

import com.bawei.mvvm.entity.ApiResponse;

import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;

import androidx.lifecycle.LiveData;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;

public class LiveDataCallAdapter<T> implements CallAdapter<T, LiveData<T>> {

        private Type responseType;
        public LiveDataCallAdapter(Type responseType) {
            this.responseType = responseType;
        }
        @Override
        public Type responseType() {
            return responseType;
        }
        @Override
        public LiveData<T> adapt(Call<T> call) {

            return new LiveData<T>() {
                AtomicBoolean start = new AtomicBoolean(false);
                @Override
                protected void onActive() {
                    super.onActive();
                    if (start.compareAndSet(false, true)){
                        call.enqueue(new Callback<T>() {
                            @Override
                            public void onResponse(Call<T> call, Response<T> response) {
                                if (200 == response.code()) {
                                        postValue(response.body());//设置属性
                                }else {
                                        ApiResponse apiResponse = new ApiResponse(response.code(),response.message());
                                        postValue((T) apiResponse);
                                }
                            }

                            @Override
                            public void onFailure(Call<T> call, Throwable t) {
                                ApiResponse apiResponse = new ApiResponse(ApiResponse.CODE_ERROR, t.getMessage());
                                postValue((T) apiResponse);
                            }
                        });
                    }
                }
            };
        }



}
